package com.zhj.rabbitmq.work.fair;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author zhj
 */
public class Work1 {
    public static void main(String[] args) {
        // 基于 amqp 协议

        // 1. 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.169.131");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        Channel channel = null;
        try {
            // 2. 创建连接对象
            connection = connectionFactory.newConnection("生产者");
            // 3. 获取通道
            channel = connection.createChannel();
            // 4. 通过通道创建交换机，声明队列，绑定关系，路由key,发送消息和接收消息
            String queueName01 = "queue01";
            // 指标 每次哪多少条
            channel.basicQos(1);
            // false 手动应答
            Channel finalChannel = channel;
            channel.basicConsume(queueName01, false, new DeliverCallback() {
                @Override
                public void handle(String s, Delivery delivery) throws IOException {
                    System.out.println("work1 收到消息是：" + new String(delivery.getBody(), "UTF-8"));
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 一定手动应答
                    finalChannel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                }
            }, new CancelCallback() {
                @Override
                public void handle(String s) throws IOException {
                    System.out.println("work1 接收消息失败！");
                }
            });
            // 5. 阻断
            System.out.println("work1 开始接收消息");
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 7. 关闭连接
            if (channel != null && channel.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 8. 关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
